Backdrop

프로그래머스 ▸ 코딩 기초 트레이닝

글자 지우기
0

문제 설명

문자열 my_string과 정수 배열 indices가 주어질 때, my_string에서 indices의 원소에 해당하는 인덱스의 글자를 지우고 이어 붙인 문자열을 return 하는 solution 함수를 작성해 주세요.

제한사항

  • 1 ≤ indices의 길이 < my_string의 길이 ≤ 100
  • my_string은 영소문자로만 이루어져 있습니다
  • 0 ≤ indices의 원소 < my_string의 길이
  • indices의 원소는 모두 서로 다릅니다.

입출력 예

my_stringindicesresult
"apporoograpemmemprs"[1, 16, 6, 15, 0, 10, 11, 3]"programmers"

입출력 예 설명

입출력 예 #1

  • 예제 1번의 my_string의 인덱스가 잘 보이도록 표를 만들면 다음과 같습니다.

    index0123456789101112131415161718
    my_stringapporoograpemmemprs

    indices에 있는 인덱스의 글자들을 지우고 이어붙이면 "programmers"가 되므로 이를 return 합니다.

풀이

문자열을 순회하면서 indices에 포함된 문자를 제외하며 새로운 문자열을 만들어요.

이론

Array.prototype.reduce()

배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환해요.

arr.reduce(callback[, initialValue]);

callback 함수는 네 개의 인자를 가져요.

  • accumulator (acc, prev) : 콜백의 반환값을 누적
  • currentValue (cur, curr) : 처리할 현재 요소
  • currentIndex (idx, index) : 처리할 현재 요소의 인덱스 (optional)
  • array (src) : reduce()를 호출한 배열 (optional)

initialValue를 제공한 경우, accinitialValue와 같고, cur는 배열의 첫 번째 요소와 같아요.

initialValue를 제공하지 않은 경우, acc는 배열의 첫 번째 요소와 같고, cur는 두 번째 요소와 같아요.

const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((prev, curr) => prev + curr, 0);
console.log(sum); // 15

map vs reduce

map()은 반환값이 같은 길이의 배열이고, reduce()는 반환값이 무엇이든 상관없어요. 주어진 조건에 따라 map()reduce() 또는 다른 메서드를 사용해야 해요.

Array.prototype.includes()

includes() 메서드는 배열의 항목에 특정 값이 포함되어 있는지를 판단하여 적절히 true 또는 false를 반환해요.

includes(searchElement[, fromIndex])
  • searchElement : 배열에서 찾을 값
  • fromIndex : 검색을 시작할 인덱스. 음수를 지정하면 배열의 끝에서부터 검색을 시작해요. 기본값은 0이에요.
const array1 = [1, 2, 3];
 
console.log(array1.includes(2));
// Expected output: true
 
const pets = ['cat', 'dog', 'bat'];
 
console.log(pets.includes('cat'));
// Expected output: true
 
console.log(pets.includes('at'));
// Expected output: false

코드

function solution(my_string, indices) {
  return [...my_string].reduce(
    (acc, cur, idx) => (indices.includes(idx) ? acc : acc + cur),
    ''
  );
}